#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import optparse
import os
import os.path
import subprocess
import sys

# Main.
if __name__ == "__main__":
    #~ Handle options.
    parser = optparse.OptionParser()
    parser.add_option( "-o", "--output-file", dest = "output",
    help = "use FILE for output, no extension required, aac automatically appended to the name", metavar = "FILE" )
    parser.add_option( "-q", "--quality", dest = "quality",
    help = "use QUALITY for encoding quality: 0.1 -> 26 kbps, 0.15 -> 37 kbps, 0.2 -> 47 kbps, 0.3 -> 80 kbps, 0.4 -> 109 kbps, 0.5 -> 168 kbps", metavar = "QUALITY" )
    ( options, args ) = parser.parse_args()
    #~ Sanity checking.
    if options.output is None:
        print( ">>>Output-file was not specified, generating one from the input file.", file = sys.stderr )
    if options.quality is None:
        print( ">>>Encoding quality was not specified!", file = sys.stderr )
        parser.parse_args( ["-h"] )
    if not len( args ):
        print( ">>>No input file specified", file = sys.stderr )
        parser.parse_args( ["-h"] )

    # Run encoding.
    if len( args ) > 1:
        print( "Warning! Multiple inputs specified, only one will be processed.", file = sys.stderr )
    sourceFile = args.pop()

    # Autogenerate output if it wasn't specified.
    if options.output is None:
        options.output = os.path.splitext( sourceFile )[0]

    # Continue with the regular program.
    command = "lame --mp2input --decode \"%s\" - " % sourceFile
    command = command + "| neroAacEnc -q %s -if - -of \"%s.aac\"" % ( options.quality, options.output )
    p = subprocess.Popen( command, shell = True )
    sts = os.waitpid( p.pid, 0 )
